<template>
  <div class="table">
    <div class="container">
      <div class="handle-box">
        <el-form ref="queryFormData" :model="queryFormData" inline size="small">
          <el-button v-if="queryFormData.singerId" type="primary" size="small" :disabled="multipleSelection.length !== 0 ? false : true"
                     icon="el-icon-delete" @click="delAll">批量失效
          </el-button>
          <el-form-item label="歌名" style="margin-left: 10px">
            <el-input v-model="queryFormData.name" clearable style="width: 120px"/>
          </el-form-item>
          <el-form-item label="歌手">
            <el-input v-model="queryFormData.singerName" clearable style="width: 120px"/>
          </el-form-item>
          <el-form-item label="专辑">
            <el-input v-model="queryFormData.albumName" clearable style="width: 120px"/>
          </el-form-item>
          <el-form-item label="有效性">
            <el-select v-model="queryFormData.dataFlag" style="width: 120px">
              <el-option :value="0" label="有效"/>
              <el-option :value="1" label="无效"/>
            </el-select>
          </el-form-item>
          <el-form-item label="页数">
            <el-input v-model="pageNum" type="number" oninput="if(value<1)value = 1" style="width: 70px"/>
          </el-form-item>
          <el-button size="small" icon="el-icon-search" @click="search">搜索</el-button>
          <el-button v-if="queryFormData.singerId" type="primary" size="small" icon="el-icon-circle-plus-outline" @click="add">添加歌曲</el-button>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="tableData" size="mini" style="width: 100%"
                @selection-change="handleSelectChanged">
        <el-table-column v-if="queryFormData.singerId" type="selection" :selectable="selectable"/>
        <el-table-column label="歌曲图片" width="110" align="center">
          <template slot-scope="{row}">
            <div class="song-img">
              <img :src="row.pic" style="width: 100%;"/>
            </div>
            <div class="play" v-if="row.url !== ''" @click="setSongUrl(row.url, row.name)">
              <div v-if="row.name === toggle">
                <svg class="icon">
                  <use xlink:href="#icon-zanting"/>
                </svg>
              </div>
              <div v-if="row.name !== toggle">
                <svg class="icon">
                  <use xlink:href="#icon-bofanganniu"/>
                </svg>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="歌名" width="150" align="center"/>
        <el-table-column prop="singerName" label="歌手" width="150" align="center"/>
        <el-table-column prop="albumName" label="专辑" width="150" align="center"/>
        <el-table-column prop="stylesStr" label="流派" width="110" align="center"/>
        <el-table-column prop="lyric" label="歌词" align="center">
          <template slot-scope="{row}">
            <p style="height: 100px; overflow: scroll">{{ row.lyric }}</p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="评论" prop="comment" width="100">
          <template slot-scope="{row}">
            <el-button size="mini" :disabled="row.dataFlag === 1" @click="comment(row.id)"
                       icon="el-icon-edit">评论
            </el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="queryFormData.singerId" align="center" label="操作" prop="operation" width="150">
          <template slot-scope="{row}">
            <el-button size="mini" @click="edit(row.id, row.singerId)">编辑</el-button>
            <el-button size="mini" :disabled="row.dataFlag === 0 ? false : true" type="danger"
                       @click="move(row.id, row.singerId)">失效
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @current-change="handleCurrentChange" background layout="prev, pager, next, total"
                       :current-page="pageNum" :page-size="pageSize" :total="total"/>
      </div>
    </div>
    <el-dialog :title="isAdd ? '添加歌曲' : '编辑歌曲'" v-if="centerDialogVisible" :visible.sync="centerDialogVisible"
               width="500px" @close="handleCancel" center :close-on-click-modal="false">
      <el-form :model="registerForm" ref="registerForm" label-width="90px" :rules="formRules" size="mini"
               v-loading="loading" label-position="left">
        <el-form-item label="歌名" prop="name" class="is-required">
          <el-input v-model="registerForm.name" clearable/>
        </el-form-item>
        <el-form-item label="专辑" prop="albumName" class="is-required">
          <el-input v-model="registerForm.albumName" clearable/>
        </el-form-item>
        <el-form-item label="图片地址" prop="pic">
          <el-input type="textarea" v-model="registerForm.pic"/>
        </el-form-item>
        <el-form-item label="mp3地址" prop="url">
          <el-input type="textarea" v-model="registerForm.url"/>
        </el-form-item>
        <el-form-item label="歌词" prop="lyric">
          <el-input type="textarea" v-model="registerForm.lyric"/>
        </el-form-item>
        <el-form-item label="流派" prop="styles" class="is-required">
          <el-checkbox-group v-model="registerForm.styles">
            <el-checkbox v-for="item of SONG_STYLES" :key="item.key" :label="item.value">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="有效性" prop="dataFlag" class="is-required">
          <el-switch v-model="registerForm.dataFlag" :active-value="0" :inactive-value="1" active-text="生效"
                     inactive-text="失效"/>
        </el-form-item>
      </el-form>
      <span slot="footer">
                <el-button size="mini" @click="handleCancel">取消</el-button>
                <el-button type="primary" size="mini" @click="addSong">确定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
// 一般工具类的引入放在业务类引入之前，避免业务类中使用工具类时出错
import {mapGetters} from 'vuex';
import '@/assets/js/iconfont.js';
import {mixin} from '../mixins';
import {SONG_STYLES} from '../constants/index';
import {listSong, getSong, saveSong, delSong} from '../api/index';

export default {
  mixins: [mixin],
  data() {
    return {
      queryFormData: {
        singerId: this.$route.query.singerId,
        name: '',
        singerName: '',
        albumName: '',
        dataFlag: 0
      },
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: true,
      centerDialogVisible: false,
      idAdd: false,
      multipleSelection: [],
      registerForm: {
        singerId: this.$route.query.singerId,
        name: '',
        albumName: '',
        styles: [],
        pic: '',
        lyric: '',
        dataFlag: '',
        url: ''
      },
      formRules: {
        name: [
          {required: true, message: '请输入歌名', trigger: 'blur'}
        ],
        albumName: [
          {required: true, message: '请输入专辑', trigger: 'blur'}
        ],
        styles: [
          {type: 'array', required: true, message: '请至少选择一个流派', trigger: 'change'}
        ]
      },
      SONG_STYLES,
      toggle: false, // 控制播放图标状态

    }
  },
  computed: {
    ...mapGetters([
      'isPlay'
    ])
  },
  mounted() {
    this.getData();
  },
  destroyed() {
    // 离开当前页面暂停播放
    this.$store.commit('setIsPlay', false);
  },
  methods: {
    getData() {
      this.loading = true;
      const {queryFormData, pageNum, pageSize} = this;
      listSong(queryFormData, pageNum, pageSize).then(res => {
        this.loading = false;
        const {data, total, success} = res;
        if (!success) {
          this.$message.error('查询失败');
          this.tableData = [];
          return;
        }
        this.tableData = data.map(e => {
          return {
            ...e,
            toggle: false
          }
        });
        this.total = total;
      })
    },
    handleCurrentChange(currentPageNum) {
      this.pageNum = currentPageNum;
      this.getData();
    },
    search() {
      this.getData();
    },
    add() {
      this.isAdd = true;
      this.centerDialogVisible = true;
      let obj = {
        singerId: this.$route.query.singerId,
        name: '',
        albumName: '',
        styles: [],
        pic: '',
        lyric: '',
        dataFlag: '',
        url: ''
      };
      this.registerForm = JSON.parse(JSON.stringify(obj));
    },
    handleCancel() {
      this.centerDialogVisible = false;
      let obj = {
        singerId: this.$route.query.singerId,
        name: '',
        albumName: '',
        styles: [],
        pic: '',
        lyric: '',
        dataFlag: '',
        url: ''
      };
      this.registerForm = JSON.parse(JSON.stringify(obj));
    },
    edit(id, singerId) {
      this.isAdd = false;
      this.centerDialogVisible = true;
      this.loading = true;
      let data = {
        id: id,
        singerId: singerId
      };
      getSong(data).then(res => {
        const {data, success} = res;
        if (success) {
          this.loading = false;
          this.registerForm = {...data};
        } else {
          this.$message.error('查询失败');
        }
      })
    },
    addSong() {
      this.$refs.registerForm.validate(isValid => {
        if (isValid) {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          saveSong(this.registerForm).then(res => {
            loading.close();
            const {success} = res;
            if (success) {
              this.$message.success("保存成功");
              this.centerDialogVisible = false;
              this.getData();
            } else {
              this.$message.error("保存失败");
            }
          });
        }
      });
    },
    del(data) {
      delSong(data).then(res => {
        const {success} = res;
        if (success) {
          this.$message.success("操作成功");
          this.getData();
        } else {
          this.$message.error("操作失败");
        }
      });
    },
    move(id, singerId) {
      this.$confirm('确定失效该记录吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          singerId: singerId,
          ids: [id]
        };
        this.del(data);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消操作'
        });
      });
    },
    delAll() {
      this.$confirm('确定批量失效吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          singerId: this.$route.query.singerId,
          ids: this.multipleSelection.map(e => e.id)
        };
        this.del(data);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消操作'
        });
      });
    },
    selectable(row) {
      return row.dataFlag === 1 ? false : true;
    },
    setSongUrl(url, name) {
      this.toggle = name;
      this.$store.commit('setUrl', url);
      if (this.isPlay) {
        this.$store.commit('setIsPlay', false);
      } else {
        this.$store.commit('setIsPlay', true);
      }
    },
    comment(id) {
      this.$router.push({path: "/Comment", query: {songId: id}});
    },
  }
}

</script>

<style scoped>
.song-img {
  width: 100%;
  height: 90px;
  margin-top: 5px;
  margin-bottom: 5px;
  overflow: hidden;
}

.play {
  position: absolute;
  z-index: 100;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  top: 18px;
  left: 15px;
}

.icon {
  width: 2em;
  height: 2em;
  color: white;
  fill: currentColor;
  overflow: hidden;
}
</style>